// main.qml
// ListWidget 适配到 Qt for HarmonyOS
// 列表组件演示：支持列表模式和图标模式切换，添加、插入、删除、编辑功能

import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15
import QtQuick.Layouts 1.15

ApplicationWindow {
    id: root
    width: Screen.width > 0 ? Screen.width : 800
    height: Screen.height > 0 ? Screen.height : 600
    visible: true
    title: "ListWidget - 列表组件演示"
    flags: Qt.Window | Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMinMaxButtonsHint | Qt.WindowCloseButtonHint
    
    // 列表数据模型
    ListModel {
        id: listModel
        
        // 初始化一些示例数据
        // ⚠️ 注意：如果图片资源不存在，使用空字符串避免崩溃
        ListElement { text: "项目 1"; iconSource: "qrc:/img/1.png" }
        ListElement { text: "项目 2"; iconSource: "qrc:/img/1.png" }
        ListElement { text: "项目 3"; iconSource: "qrc:/img/1.png" }
    }
    
    // 当前选中的项文本
    property string currentItemText: ""
    
    // 视图模式：true = 列表模式，false = 图标模式
    property bool isListMode: true
    
    // 当前选中的索引（用于插入操作）
    property int currentIndex: -1
    
    // 初始化
    Component.onCompleted: {
        console.log("ListWidget: ApplicationWindow onCompleted")
        
        // ⚠️ 关键：确保窗口激活并获得焦点，这样才能接收事件
        console.log("ListWidget: Requesting window activation")
        root.show()
        root.requestActivate()
        console.log("ListWidget: Window active:", root.active)
    }
    
    // 添加项
    function addItem() {
        var inputText = inputField.text.trim()
        if (inputText === "") {
            console.log("ListWidget: 输入为空，无法添加")
            return
        }
        
        console.log("ListWidget: 添加项:", inputText)
        try {
            listModel.append({
                text: inputText,
                iconSource: "qrc:/img/1.png"
            })
        } catch (e) {
            console.error("ListWidget: 添加项失败:", e)
        }
        inputField.text = ""
        console.log("ListWidget: 列表项数量:", listModel.count)
    }
    
    // 插入项
    function insertItem() {
        var inputText = inputField.text.trim()
        if (inputText === "") {
            console.log("ListWidget: 输入为空，无法插入")
            return
        }
        
        if (currentIndex < 0 || currentIndex >= listModel.count) {
            console.log("ListWidget: 无效的索引，改为添加")
            addItem()
            return
        }
        
        console.log("ListWidget: 在索引", currentIndex, "插入项:", inputText)
        try {
            listModel.insert(currentIndex, {
                text: inputText,
                iconSource: "qrc:/img/1.png"
            })
        } catch (e) {
            console.error("ListWidget: 插入项失败:", e)
        }
        inputField.text = ""
        console.log("ListWidget: 列表项数量:", listModel.count)
    }
    
    // 删除项
    function deleteItem() {
        if (currentIndex < 0 || currentIndex >= listModel.count) {
            console.log("ListWidget: 没有选中的项，无法删除")
            return
        }
        
        console.log("ListWidget: 删除索引", currentIndex, "的项")
        try {
            if (currentIndex >= 0 && currentIndex < listModel.count) {
                listModel.remove(currentIndex)
                currentIndex = -1
                currentItemText = ""
                console.log("ListWidget: 列表项数量:", listModel.count)
            } else {
                console.warn("ListWidget: 无效的索引，无法删除")
            }
        } catch (e) {
            console.error("ListWidget: 删除项失败:", e)
        }
    }
    
    Rectangle {
        id: contentRect
        anchors.fill: parent
        color: "#F5F5F5"
        
        Column {
            anchors.fill: parent
            anchors.margins: 40
            spacing: 30
            
            // 列表/图标模式切换
            Row {
                width: parent.width
                spacing: 40
                height: 80
                
                Text {
                    text: "视图模式："
                    width: 150
                    height: parent.height
                    verticalAlignment: Text.AlignVCenter
                    font.pixelSize: 36
                    font.bold: true
                }
                
                RadioButton {
                    id: listModeRadio
                    text: "列表模式"
                    checked: isListMode
                    font.pixelSize: 36
                    height: parent.height
                    
                    onCheckedChanged: {
                        if (checked) {
                            isListMode = true
                            console.log("ListWidget: 切换到列表模式")
                        }
                    }
                }
                
                RadioButton {
                    id: iconModeRadio
                    text: "图标模式"
                    checked: !isListMode
                    font.pixelSize: 36
                    height: parent.height
                    
                    onCheckedChanged: {
                        if (checked) {
                            isListMode = false
                            console.log("ListWidget: 切换到图标模式")
                        }
                    }
                }
            }
            
            // 列表视图区域（使用 ScrollView 包装，避免截断）
            ScrollView {
                width: parent.width
                height: parent.height - 400  // 增加底部空间
                clip: true
                
                Rectangle {
                    width: parent.width
                    height: isListMode ? listView.contentHeight + 20 : gridView.contentHeight + 20
                    color: "white"
                    border.color: "#CCCCCC"
                    border.width: 2
                    radius: 10
                
                // 列表模式
                ListView {
                    id: listView
                    anchors.fill: parent
                    anchors.margins: 10
                    visible: isListMode
                    model: listModel
                    spacing: 2
                    clip: true
                    
                    delegate: Rectangle {
                        id: listItemDelegate
                        width: listView.width
                        height: 100  // 增大列表项高度
                        color: index % 2 === 0 ? "#FFFFFF" : "#F8F8F8"  // 交替行颜色
                        border.color: listItemDelegate.ListView.isCurrentItem ? "#0078D4" : "transparent"
                        border.width: listItemDelegate.ListView.isCurrentItem ? 3 : 0
                        radius: 8
                        
                        Row {
                            anchors.fill: parent
                            anchors.margins: 15
                            spacing: 20
                            
                            // 图标
                            Image {
                                width: 80
                                height: 80
                                source: iconSource || ""
                                fillMode: Image.PreserveAspectFit
                                anchors.verticalCenter: parent.verticalCenter
                                asynchronous: true
                                
                                // 图片加载失败时的占位符
                                Rectangle {
                                    anchors.fill: parent
                                    color: "#E0E0E0"
                                    visible: parent.status === Image.Error || parent.status === Image.Null
                                    radius: 5
                                    
                                    Text {
                                        anchors.centerIn: parent
                                        text: "📷"
                                        font.pixelSize: 30
                                        color: "#999999"
                                    }
                                }
                                
                                onStatusChanged: {
                                    if (status === Image.Error) {
                                        console.log("ListWidget: 图片加载失败:", iconSource)
                                    }
                                }
                            }
                            
                            // 文本（可编辑）
                            TextInput {
                                id: listItemText
                                width: parent.width - 120
                                height: parent.height
                                verticalAlignment: TextInput.AlignVCenter
                                font.pixelSize: 40
                                color: "#333333"
                                text: model.text || ""
                                selectByMouse: true
                                readOnly: !isEditing
                                
                                property bool isEditing: false
                                
                                onEditingFinished: {
                                    if (isEditing) {
                                        try {
                                            if (index >= 0 && index < listModel.count) {
                                                listModel.setProperty(index, "text", text)
                                                console.log("ListWidget: 编辑完成，新文本:", text)
                                            } else {
                                                console.warn("ListWidget: 无效的索引，无法编辑")
                                            }
                                        } catch (e) {
                                            console.error("ListWidget: 编辑失败:", e)
                                        }
                                        isEditing = false
                                    }
                                }
                                
                                // 点击事件由外层的 MouseArea 处理
                            }
                        }
                        
                        // 点击效果
                        Rectangle {
                            anchors.fill: parent
                            color: "#E0E0E0"
                            opacity: mouseArea.pressed ? 0.5 : 0
                            Behavior on opacity {
                                NumberAnimation { duration: 100 }
                            }
                        }
                        
                        MouseArea {
                            id: mouseArea
                            anchors.fill: parent
                            onClicked: {
                                // 如果正在编辑，不处理点击
                                if (listItemText.isEditing) {
                                    return
                                }
                                currentIndex = index
                                currentItemText = model.text
                                listView.currentIndex = index
                                console.log("ListWidget: 选中项索引:", index, "文本:", model.text)
                            }
                            
                            onDoubleClicked: {
                                // 双击进入编辑模式
                                if (!listItemText.isEditing) {
                                    try {
                                        listItemText.isEditing = true
                                        listItemText.forceActiveFocus()
                                        listItemText.selectAll()
                                        console.log("ListWidget: 开始编辑项:", index)
                                    } catch (e) {
                                        console.error("ListWidget: 开始编辑失败:", e)
                                    }
                                }
                            }
                        }
                    }
                    
                    highlight: Rectangle {
                        color: "#E3F2FD"
                        radius: 5
                    }
                }
                
                // 图标模式（GridView）
                GridView {
                    id: gridView
                    anchors.fill: parent
                    anchors.margins: 15
                    visible: !isListMode
                    model: listModel
                    cellWidth: 180  // 增大单元格宽度
                    cellHeight: 180  // 增大单元格高度
                    clip: true
                    
                    delegate: Rectangle {
                        id: gridItemDelegate
                        width: gridView.cellWidth - 20
                        height: gridView.cellHeight - 20
                        color: gridItemDelegate.GridView.isCurrentItem ? "#E3F2FD" : "#FFFFFF"
                        border.color: gridItemDelegate.GridView.isCurrentItem ? "#0078D4" : "#CCCCCC"
                        border.width: gridItemDelegate.GridView.isCurrentItem ? 3 : 1
                        radius: 12
                        
                        Column {
                            anchors.fill: parent
                            anchors.margins: 10
                            spacing: 10
                            
                            // 图标
                            Image {
                                width: parent.width
                                height: parent.height - 50
                                source: iconSource || ""
                                fillMode: Image.PreserveAspectFit
                                anchors.horizontalCenter: parent.horizontalCenter
                                asynchronous: true
                                
                                // 图片加载失败时的占位符
                                Rectangle {
                                    anchors.fill: parent
                                    color: "#E0E0E0"
                                    visible: parent.status === Image.Error || parent.status === Image.Null
                                    radius: 5
                                    
                                    Text {
                                        anchors.centerIn: parent
                                        text: "📷"
                                        font.pixelSize: 40
                                        color: "#999999"
                                    }
                                }
                                
                                onStatusChanged: {
                                    if (status === Image.Error) {
                                        console.log("ListWidget: 图片加载失败:", iconSource)
                                    }
                                }
                            }
                            
                            // 文本（可编辑）
                            Item {
                                width: parent.width
                                height: 50
                                
                                // 显示模式下的 Text
                                Text {
                                    id: gridItemText
                                    anchors.fill: parent
                                    horizontalAlignment: Text.AlignHCenter
                                    verticalAlignment: Text.AlignVCenter
                                    font.pixelSize: 28
                                    color: "#333333"
                                    text: model.text || ""
                                    elide: Text.ElideRight
                                    visible: !gridItemTextInput.isEditing  // ⚠️ 编辑时隐藏
                                }
                                
                                // 编辑模式下的 TextInput
                                TextInput {
                                    id: gridItemTextInput
                                    anchors.fill: parent
                                    horizontalAlignment: TextInput.AlignHCenter
                                    verticalAlignment: TextInput.AlignVCenter
                                    font.pixelSize: 28
                                    color: "#333333"
                                    visible: isEditing
                                    selectByMouse: true
                                    
                                    property bool isEditing: false
                                    
                                    onEditingFinished: {
                                        if (isEditing) {
                                            try {
                                                if (index >= 0 && index < listModel.count) {
                                                    listModel.setProperty(index, "text", text)
                                                    console.log("ListWidget: 编辑完成，新文本:", text)
                                                } else {
                                                    console.warn("ListWidget: 无效的索引，无法编辑")
                                                }
                                            } catch (e) {
                                                console.error("ListWidget: 编辑失败:", e)
                                            }
                                            isEditing = false
                                        }
                                    }
                                }
                            }
                        }
                        
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                if (!gridItemTextInput.isEditing) {
                                    try {
                                        currentIndex = index
                                        currentItemText = model.text || ""
                                        gridView.currentIndex = index
                                        console.log("ListWidget: 选中项索引:", index, "文本:", model.text)
                                    } catch (e) {
                                        console.error("ListWidget: 选中项失败:", e)
                                    }
                                }
                            }
                            
                            onDoubleClicked: {
                                try {
                                    gridItemTextInput.isEditing = true
                                    gridItemTextInput.text = model.text || ""
                                    gridItemTextInput.forceActiveFocus()
                                    gridItemTextInput.selectAll()
                                    console.log("ListWidget: 开始编辑项:", index)
                                } catch (e) {
                                    console.error("ListWidget: 开始编辑失败:", e)
                                }
                            }
                        }
                    }
                    
                    highlight: Rectangle {
                        color: "#E3F2FD"
                        radius: 12
                    }
                }
                }
            }
            
            // 当前选中项显示
            Row {
                width: parent.width
                spacing: 30
                height: 80
                
                Text {
                    text: "当前条目："
                    width: 180
                    height: parent.height
                    verticalAlignment: Text.AlignVCenter
                    font.pixelSize: 36
                    font.bold: true
                }
                
                Rectangle {
                    width: parent.width - 170
                    height: parent.height
                    color: "white"
                    border.color: "#CCCCCC"
                    border.width: 2
                    radius: 8
                    
                    Text {
                        anchors.fill: parent
                        anchors.margins: 15
                        verticalAlignment: Text.AlignVCenter
                        font.pixelSize: 36
                        color: "#333333"
                        text: currentItemText || "未选择"
                    }
                }
            }
            
            // 输入框
            Rectangle {
                width: parent.width
                height: 80
                color: "white"
                border.color: inputField.activeFocus ? "#0078D4" : "#CCCCCC"
                border.width: inputField.activeFocus ? 3 : 2
                radius: 10
                
                TextInput {
                    id: inputField
                    anchors.fill: parent
                    anchors.margins: 15
                    verticalAlignment: TextInput.AlignVCenter
                    font.pixelSize: 36
                    color: "#333333"
                    selectByMouse: true
                    
                    Keys.onReturnPressed: {
                        addItem()
                    }
                }
                
                // 手动实现 placeholder 效果
                Text {
                    anchors.fill: inputField
                    anchors.margins: 15
                    verticalAlignment: Text.AlignVCenter
                    font.pixelSize: 36
                    color: "#999999"
                    text: "请输入项目名称"
                    visible: !inputField.activeFocus && inputField.text === ""
                }
            }
            
            // 按钮行
            Row {
                width: parent.width
                spacing: 40
                height: 90
                
                Button {
                    text: "添加"
                    width: (parent.width - 80) / 3
                    height: parent.height
                    font.pixelSize: 36
                    
                    onClicked: {
                        console.log("ListWidget: 添加按钮被点击")
                        addItem()
                    }
                }
                
                Button {
                    text: "插入"
                    width: (parent.width - 80) / 3
                    height: parent.height
                    font.pixelSize: 36
                    
                    onClicked: {
                        console.log("ListWidget: 插入按钮被点击")
                        insertItem()
                    }
                }
                
                Button {
                    text: "删除"
                    width: (parent.width - 80) / 3
                    height: parent.height
                    font.pixelSize: 36
                    
                    onClicked: {
                        console.log("ListWidget: 删除按钮被点击")
                        deleteItem()
                    }
                }
            }
        }
    }
}
